#include"DSL.h"

ListNode* ListCreate()
{
	ListNode* head = (ListNode*)malloc(sizeof(ListNode));
	head->_data = -1;
	head->_next = head;
	head->_prev = head;
	return head;
}
ListNode* Buynewnode(int x)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	newnode->_data = x;
}
void ListPushBack(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	//ListNode* newnode = Buynewnode(x);
	//ListNode* tail = pHead->_prev;
	////newnode->_next = pHead;
	//newnode->_prev = tail;
	//tail->_next = newnode;
	//pHead->_prev = newnode;
	ListInsert(pHead,x);
}

void ListPrint(ListNode* pHead)
{
	assert(pHead);
	ListNode* cur = pHead->_next;
	printf("<=>phead<=>");
	while (cur!=pHead)
	{
		printf("%d<=>", cur->_data);
		cur = cur->_next;
	}
	printf("\n");
}
void ListDestory(ListNode* pHead)
{
	assert(pHead);
	ListNode* cur = pHead;
	ListNode* next;
	do {
		next = cur->_next;
		free(cur);
		cur = next;
	} while (pHead != cur);
}
void ListPopBack(ListNode* pHead)
{
	assert(pHead);

	/*ListNode* tail = pHead->_prev;
	ListNode* pre = tail->_prev;
	free(tail);
	tail = NULL;
	pHead->_prev = pre;
	pre->_next = pHead;*/
	ListErase(pHead->_prev);
}
void ListPushFront(ListNode* pHead, LTDataType x)
{
	assert(pHead);

	//ListNode* newnode = Buynewnode(x);
	ListNode* pre = pHead->_next;
	//newnode->_next = pre;
	//pre->_prev = newnode;
	//newnode->_prev = pHead;
	//pHead->_next = newnode;
	ListInsert(pre,x);
}
void ListPopFront(ListNode* pHead)
{
	assert(pHead);

	//ListNode* next = pHead->_next->_next;
	//ListNode* cur = pHead->_next;
	//pHead->_next = next;
	//next->_prev = pHead;
	//free(cur);
	//cur = NULL;
	ListErase(pHead->_next);
}
ListNode* ListFind(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	ListNode* cur = pHead->_next;
	while (pHead!=cur)
	{
		if (cur->_data == x)
		{
			return cur;
		}
		cur = cur->_next;
	}
	return NULL;

}
void ListInsert(ListNode* pos, LTDataType x)
{
	assert(pos);
	ListNode* pre = pos->_prev;
	ListNode* newnode = Buynewnode(x);
	newnode->_next = pos;
	pos->_prev = newnode;
	newnode->_prev = pre;
	pre->_next = newnode;
}
void ListErase(ListNode* pos)
{
	assert(pos);
	ListNode* pre = pos->_prev;
	ListNode* next = pos->_next;
	pre->_next = next;
	next->_prev = pre;
	free(pos);
	pos = NULL;

}

